import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:znmm/UI/CartPages/mag/cart_mag.dart';
import 'package:znmm/UI/LoginPages/mag/user_info_manage.dart';
import 'package:znmm/UI/A_Common/buttons/counter_button.dart';
import 'package:znmm/UI/A_Common/buttons/easy_button/easy_elevated_button.dart';
import 'package:znmm/UI/A_Common/custom_web_view.dart';
import 'package:znmm/UI/A_Common/dialogs/cn_custom_dialog.dart';
import 'package:znmm/UI/A_Common/image_banner_slider.dart';
import 'package:znmm/UI/A_Common/image_selector.dart';
import 'package:znmm/UI/A_Common/star_rating_bar.dart';
import 'package:znmm/UI/utils/my_global.dart';
import 'package:znmm/config/app_color.dart';
import 'package:znmm/config/app_init.dart';
import 'package:share_plus/share_plus.dart';
import '../../../config/app_asset.dart';
import '../A_Common/image/cached_network_Image.dart';
import '../A_Common/size_selector.dart';
import 'mag/product_mag.dart';
import 'model/attributes_model.dart';
import 'model/product_model.dart';

class ShowProductView extends StatefulWidget {
  final ProductModel product;
  const ShowProductView({Key? key, required this.product}) : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  _ShowProductViewState createState() => _ShowProductViewState();
}

class _ShowProductViewState extends State<ShowProductView> {
  final GlobalKey<ProductBannerSliderState> _glKey =
      GlobalKey<ProductBannerSliderState>();

  int _iQty = 0;
  String _sourceUrl = ""; //更换url
  List<String> _attriTitleList = []; //标题
  List<String> _selAttriStrList = []; //选择
  VariationsModel? _variatModel;

  String _selColor = "";

  @override
  void initState() {
    super.initState();

    // 使用列表推导式初始化_selAttributes列表
    _selAttriStrList = List.filled(
      widget.product.attriModelList.length,
      "",
    );

    _attriTitleList = List.filled(
      widget.product.attriModelList.length,
      "",
    );
  }

  @override
  Widget build(BuildContext context) {
    double fPand = 10.0;
    ProductModel pmodel = widget.product;

    List<Widget> widgetList = [];
    widgetList.add(const SizedBox(
      height: 5,
    ));

    if (_sourceUrl.isNotEmpty) {
      widgetList.add(SizedBox(
        //width: MediaQuery.of(context).size.width,
        height: 320,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(10.0),
          child: CachedNetworkImageLoader(
            imageUrl: _sourceUrl,
            fit: BoxFit.fill,
          ),
        ),
      ));
    } else {
      widgetList.add(ImageBannerSlider(
          key: _glKey,
          bIsNetworkImage: pmodel.galleryImagesList.isNotEmpty ? true : false,
          productImages: pmodel.galleryImagesList.isNotEmpty
              ? pmodel.galleryImagesList
              : pmodel.imagesList));

      widgetList.add(ImageSelector(
        onClickTap: (icount) {
          //print("icount:$icount");
          if (_glKey.currentState != null) {
            _glKey.currentState!.setCurrentPage(icount);
          }
        },
        bIsNetworkImage: pmodel.galleryImagesList.isNotEmpty ? true : false,
        productImages: pmodel.galleryImagesList.isNotEmpty
            ? pmodel.galleryImagesList
            : pmodel.imagesList,
      ));
    }

    widgetList.add(Padding(
      padding: EdgeInsets.fromLTRB(fPand, 15, fPand, 0),
      child: Text(widget.product.name,
          style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
    ));

    widgetList.add(Padding(
        padding: EdgeInsets.fromLTRB(fPand, 10, fPand, 0),
        child: Row(
          children: [
            _producScore(widget.product),
            Container(
              height: 36,
              margin: const EdgeInsets.fromLTRB(20, 0, 0, 0),
              padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                //color: Colors.black,
                border: Border.all(
                  color: Colors.black,
                  width: 1.0,
                ),
                borderRadius: BorderRadius.circular(18.0), // 设置圆角半径为10
              ),
              child: Text(
                pmodel.stockStatus,
                style: TextStyle(
                    color: pmodel.stockStatus == "OUT_OF_STOCK"
                        ? Colors.red
                        : Colors.black,
                    fontSize: 16,
                    fontWeight: FontWeight.bold),
              ),
            ),
            Expanded(
                child: GestureDetector(
              onTap: () {
                Get.to(CustomWebView(
                  titleStr: "Add To Cart",
                  initialUrl: widget.product.link,
                ));
              },
              child: Container(
                height: 36,
                margin: const EdgeInsets.fromLTRB(10, 0, 5, 0),
                // padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Colors.black,
                  borderRadius: BorderRadius.circular(18.0), // 设置圆角半径为10
                ),
                child: const Text(
                  "link",
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.bold),
                ),
              ),
            ))
          ],
        )));

    widgetList.add(Padding(
      padding: EdgeInsets.fromLTRB(fPand, 10, fPand, 0),
      child: Row(
        children: [
          Text(widget.product.price,
              style:
                  const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
        ],
      ),
    ));

    for (int iIndex = 0; iIndex < pmodel.attriModelList.length; iIndex++) {
      AttributesModel attrModel = pmodel.attriModelList[iIndex];
      _attriTitleList[iIndex] = attrModel.label;
      widgetList.add(Padding(
          padding: EdgeInsets.fromLTRB(fPand, 15, fPand, 0),
          child: Row(
            children: [
              Text(
                attrModel.label,
                style:
                    const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                textAlign: TextAlign.end,
              ),
              const SizedBox(
                width: 10,
              ),
              Expanded(
                  child: SizeSelector(
                padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
                sizes: attrModel.options,
                onSizeSelected: (String selectedSize) {
                  // 处理
                  print("${attrModel.label}:$selectedSize");
                  _selAttriStrList[iIndex] = selectedSize;
                  print("leng:${pmodel.variaModelList.length}");

                  bool bIsSelAll = true; //所有都选了
                  String selAllStr = "";
                  for (int iIndex = 0;
                      iIndex < _selAttriStrList.length;
                      iIndex++) {
                    selAllStr = selAllStr + _selAttriStrList[iIndex];

                    if (_selAttriStrList[iIndex].isEmpty) {
                      bIsSelAll = false;
                    }
                  }
                  _selColor = selAllStr;
                  print("_selColor:$selAllStr bIsSelAll:$bIsSelAll");

                  VariationsModel? varMo =
                      pmodel.findVariationByTagKey(selAllStr, bIsSelAll);
                  _variatModel = varMo;
                  //刷新
                  setState(() {
                    if (varMo != null) {
                      _sourceUrl = varMo.sourceUrl;
                      print("_sourceUrl:$_sourceUrl");
                    } else {
                      _sourceUrl = "";
                    }
                  });
                },
              )),
            ],
          )));
    }

    //if (pmodel.stockStatus != "OUT_OF_STOCK")
    {
      widgetList.add(Padding(
          padding: EdgeInsets.fromLTRB(fPand, 10, fPand, 0),
          child: Row(
            children: [
              const Text(
                "QTY",
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                textAlign: TextAlign.end,
              ),
              const SizedBox(
                width: 10,
              ),
              CounterButton(
                onIncrementSelected: (int iQty) {
                  _iQty = iQty;
                },
                onDecrementSelected: (int iQty) {
                  _iQty = iQty;
                },
              )
            ],
          )));
    }

    widgetList.add(const Padding(
      padding: EdgeInsets.fromLTRB(5, 10, 5, 10),
      child: Divider(
        color: Colors.grey,
        thickness: 1,
      ),
    ));

    widgetList.add(Padding(
        padding: EdgeInsets.fromLTRB(fPand, 0, fPand, 0),
        child: Row(
          children: [
            const Text(
              "Category:",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              textAlign: TextAlign.end,
            ),
            const SizedBox(
              width: 10,
            ),
            Text(
              widget.product.productCateName,
              style: const TextStyle(
                fontSize: 16,
              ),
              textAlign: TextAlign.end,
            ),
          ],
        )));

    widgetList.add(Padding(
        padding: EdgeInsets.fromLTRB(fPand, 10, fPand, 0),
        child: const Row(
          children: [
            Text(
              "Quantity:",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              textAlign: TextAlign.end,
            ),
            SizedBox(
              width: 10,
            ),
            Text(
              "N/A",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              textAlign: TextAlign.end,
            ),
          ],
        )));

    widgetList.add(_shareOn(fPand));

    widgetList.add(const SizedBox(
      height: 50,
    ));

    return Scaffold(
      backgroundColor: AppColor.backgroundColor,
      bottomNavigationBar: bottomBar(),
      appBar: MyGlobal.getNavigationBar(context, 'shopping'),
      body: SingleChildScrollView(
          child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: widgetList,
      )),
    );
  }

  //------------Share On
  Widget _shareOn(double fPand) {
    return Padding(
      padding: EdgeInsets.fromLTRB(fPand, 10, fPand, 0),
      child: Row(
        children: [
          const Text(
            "Share On",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            textAlign: TextAlign.end,
          ),
          const SizedBox(
            width: 20,
          ),
          GestureDetector(
              onTap: () {
                _shareContent("Facebook");
              },
              child: Image.asset(
                width: 36,
                height: 36,
                AppAsset.imageFacebook,
                fit: BoxFit.fill,
              )),
          const SizedBox(
            width: 10,
          ),
          GestureDetector(
              onTap: () {
                _shareContent("Twitter");
              },
              child: Image.asset(
                width: 36,
                height: 36,
                AppAsset.imageTwitter,
                fit: BoxFit.fill,
              )),
          const SizedBox(
            width: 10,
          ),
          GestureDetector(
              onTap: () {
                _shareContent("Linkedin");
              },
              child: Image.asset(
                width: 36,
                height: 36,
                AppAsset.imageLinkedin,
                fit: BoxFit.fill,
              )),
          const SizedBox(
            width: 10,
          ),
          GestureDetector(
              onTap: () {
                _shareContent("Whatsapp");
              },
              child: Image.asset(
                width: 36,
                height: 36,
                AppAsset.imageWhatsapp,
                fit: BoxFit.fill,
              )),
        ],
      ),
    );
  }

  void _shareContent(String strContent) {
    Share.share(
      strContent,
    );
  }

  //------------bottomBar
  Widget bottomBar() {
    print("widget.product.price:${widget.product.price}");
    return Container(
      padding: const EdgeInsets.all(15),
      height: 90,
      child: Row(
        //mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                'Price',
                style: TextStyle(
                  color: Colors.black45,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 5),
              Text(widget.product.price,
                  style: const TextStyle(
                      color: Colors.black,
                      fontSize: 16,
                      fontWeight: FontWeight.bold))
            ],
          )),
          EasyElevatedButton(
            label: "Add to cart",
            isRounded: true,
            color: Colors.black,
            onPressed: () {
              _addToCart();
            },
          ),
          const SizedBox(
            width: 5,
          ),
          EasyElevatedButton(
            label: "Buy Now",
            isRounded: true,
            color: Colors.black,
            onPressed: () {
              _addToCart(iType: 1);
            },
          )
        ],
      ),
    );
  }

  //请求
  void _addToCart({int iType = 0}) {
    if (UserInfoMag().bIsVisito) {
      _showTips();
      return;
    }

    if (_variatModel != null || widget.product.attriModelList.isEmpty) {
      if (widget.product.attriModelList.isEmpty &&
          widget.product.stockStatus == "OUT_OF_STOCK") {
        MyGlobal.showInfo("OUT_OF_STOCK");
        return;
      }

      ProductMag().addToCartReq(
        widget.product,
        _variatModel,
        _iQty,
        _selAttriStrList,
        _sourceUrl,
        _selColor,
        callback: () {
          if (iType == 0) {
            CnCartMag().reqCartData(
              callback: () {
                Get.back();
              },
            );
          } else {
            UserInfoMag().jumpToBottomPage(2);
          }
        },
      );
    } else {
      bool bIsShow = false;
      for (int iIndex = 0; iIndex < _selAttriStrList.length; iIndex++) {
        if (_selAttriStrList[iIndex].isEmpty) {
          MyGlobal.showInfo(_attriTitleList[iIndex]);
          bIsShow = true;
          break;
        }
      }

      if (!bIsShow) {
        //MyGlobal.showInfo("Error...");

        ProductMag().addToCartReq(
          widget.product,
          _variatModel,
          _iQty,
          _selAttriStrList,
          _sourceUrl,
          _selColor,
          callback: () {
            if (iType == 0) {
              Get.back();
            } else {
              UserInfoMag().jumpToBottomPage(2);
            }
          },
        );
      }
    }
  }

  void _showTips() {
    showDialog(
      context: context,
      builder: (context) => const CustomDialog(
        content: 'Please Login?',
        confirmText: "Login",
      ),
    ).then((value) {
      if (value != null && value) {
        AppInit.logoutDispose();
      }
    });
  }

  //------------_producScore
  Widget _producScore(ProductModel product) {
    return Row(
      children: [
        StarRatingBar(score: product.averageRating),
        const SizedBox(width: 10),
        Text(product.averageRating.toString(),
            style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
      ],
    );
  }
}
